/* eslint-disable */
import React, { useEffect, useRef, useState } from 'react';
import { Button, Progress } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import { guideProps } from './interface';
import Draggable from 'react-draggable';
import './index.scss';
import { getFeature } from 'utils/features';

const foldUp = require('./fold-up.svg');

// const close = require('../../image/close.svg');

let isClick = false;

interface IProject {
  name: string;
  active: boolean;
  status: boolean;
  message: React.ReactNode;
  title: string;
  step?: string;
  image?: string;
  subMessage?: string;
  completeTitle?: string;
}

const CodeUpGuide: React.FC<guideProps> = ({
  guideCreateProject,
  guideStatus = { step: 0, active: true, status: false },
  guidePropsCount = 0,
  isRepoMaster = false,
  isRepoMasterHander,
  isRepomasterOk,
  onChangePropsCount,
  onCloseGuide,
  onChangeStep,
  track,
}) => {
  const [guideCount, setGuideCount] = useState<number>(0);
  const ref = useRef(null);
  const codeupRef = useRef(null);

  useEffect(() => {
    if (guidePropsCount > 0) {
      setGuideCount(guidePropsCount);
    }
  }, [guidePropsCount]);
  const stepName = ['', 'repo', 'branch', 'flow', 'scan', 'mr', 'finish'];
  const [array, setArray] = useState<IProject[]>([
    {
      name: '1',
      active: false,
      status: true,
      message: <span>欢迎访问你的代码库</span>,
      subMessage: '现在开始库内探索旅程吧',
      title: '创建代码库',
      image:
        'https://img.alicdn.com/imgextra/i3/O1CN01bGSXRA1CAov70yoQ6_!!6000000000041-2-tps-600-240.png',
      completeTitle: '&#128079 已创建代码库',
      step: 'repo',
    },
    {
      name: '2',
      active: false,
      status: false,
      message: (
        <span>
          可通过快速初始化或命令行提交
          <a
            target="_blank"
            onClick={() => track('help-branch')}
            href="https://help.aliyun.com/document_detail/153708.html"
            rel="noreferrer"
          >
            了解更多
          </a>
        </span>
      ),
      title: '提交代码',
      image:
        'https://img.alicdn.com/imgextra/i3/O1CN010zGYP91VJV7pqbnNe_!!6000000002632-2-tps-600-240.png',
      completeTitle: '&#128077 已提交代码',
      step: 'branch',
    },
    {
      name: '3',
      active: false,
      status: false,
      message: (
        <span>
          体验测试与持续集成功能
          <a
            target="_blank"
            onClick={() => track('help-flow')}
            href="https://help.aliyun.com/document_detail/206834.html"
            rel="noreferrer"
          >
            了解更多
          </a>
        </span>
      ),
      title: '创建自动化流水线',
      image:
        'https://img.alicdn.com/imgextra/i3/O1CN016N0IxL1yHK6KFKvak_!!6000000006553-2-tps-600-240.png',
      completeTitle: '&#127881 已创建流水线',
      step: 'flow',
    },
    {
      name: '4',
      active: false,
      status: true,
      message: (
        <span>
          屏蔽编码漏洞、敏感信息泄露、三方依赖包漏洞等高危安全隐患&nbsp;&nbsp;
          <a
            style={{ display: 'inline-block' }}
            onClick={() => track('help-scan')}
            target="_blank"
            href="https://help.aliyun.com/document_detail/153723.html"
            rel="noreferrer"
          >
            了解更多
          </a>
        </span>
      ),
      title: '启用代码安全检测',
      image:
        'https://img.alicdn.com/imgextra/i4/O1CN01HgNwOh1JlBgEA9eAH_!!6000000001068-2-tps-600-240.png',
      completeTitle: '&#127882 已启用代码检查',
      step: 'scan',
    },
    {
      name: '&#127881',
      active: true,
      status: true,
      message: (
        <span>
          人工审查+自动检查代码缺陷
          <br />
          保证合并质量&nbsp;&nbsp;
          <a
            style={{ display: 'inline-block' }}
            onClick={() => track('help-mr')}
            target="_blank"
            href="https://help.aliyun.com/document_detail/153871.html"
            rel="noreferrer"
          >
            了解更多
          </a>
        </span>
      ),
      title: '创建代码评审',
      image:
        'https://img.alicdn.com/imgextra/i3/O1CN01mJsncc1CCeVKvJFcO_!!6000000000045-2-tps-600-240.png',
      completeTitle: '&#128204 已创建代码评审',
      step: 'mr',
    },
    {
      name: '6',
      active: true,
      status: true,
      message: (
        <span>
          想要了解更多高级能力？{' '}
          <a
            target="_blank"
            href="https://help.aliyun.com/document_detail/258251.html"
            rel="noreferrer"
          >
            立刻前往
          </a>
        </span>
      ),
      title: '真棒！基础能力已全部掌握&#128077',
      image:
        'https://img.alicdn.com/imgextra/i4/O1CN01k6uLMK1PROFtRa74b_!!6000000001837-2-tps-600-240.png',
      // completeTitle: '📌 已创建代码评审',
    },
  ]);
  useEffect(() => {
    if (guideStatus && guideStatus.step > -1) {
      const arrValue = array.map((vx, idx) => {
        if (guideStatus.step === idx) {
          return { ...vx, status: guideStatus.status, active: guideStatus.active };
        } else if (guideStatus.step > idx) {
          return { ...vx, status: true, active: false };
        } else {
          return { ...vx, status: false, active: false };
        }
      });
      setArray(arrValue);
    }
  }, [guideStatus.step, guideStatus.active, guideStatus.status]);
  useEffect(() => {
    const dom = codeupRef.current;
    if (dom) {
      dom.style.display = 'block';
    }
  }, [guideCount]);

  const closeGuide = () => {
    const dom = codeupRef.current;
    track &&
      track('close_new_user_tips', {
        type: guideStatus && guideStatus.step ? stepName[guideStatus.step + 1] || '' : '',
      });
    if (dom) {
      if (onCloseGuide) {
        onCloseGuide(dom);
      }
      dom.style.display = 'none';
    }
  };

  const guideConent = (number: number): any => {
    switch (number) {
      case 0:
        return guideOne;
      case 1:
        return guideTwo;
      case 2:
        return guideThree();
      case 3:
        return guideFour;
      case 4:
        return guideFives;
      default:
        return null;
    }
  };
  const guideOne = (
    <div className="codeUp-guideOne">
      <div className="codeUp-guideOne-title">创建你的代码库</div>
      <div className="codeUp-guideOne-conect">
        示例库为你展示了 Codeup 主要功能，立即创建代码库体验免费、高效、安全的托管服务吧
      </div>
      <div className="codeUp-guideOne-buttonGroup">
        <Button
          type="primary"
          className="createButton"
          onClick={() => {
            track('create-new-repo');
            guideCreateProject && guideCreateProject();
          }}
        >
          立即创建
        </Button>
        <Button className="ignore" onClick={() => closeGuide()}>
          忽略
        </Button>
      </div>
    </div>
  );
  const guideFour = (
    <div className="codeUp-guideOne">
      <div
        className="codeUp-guideOne-title"
        dangerouslySetInnerHTML={{ __html: '&#128161 智能评审，轻松规划优先级' }}
      />
      <div className="codeUp-guideOne-conect">
        「智能评审」支持预估每个合并请求的评审耗时，快去试试吧。
      </div>
      <div className="codeUp-guideOne-buttonGroup">
        <Button
          type="primary"
          className="createButton"
          onClick={() => {
            isRepoMasterHander && isRepoMasterHander();
          }}
        >
          {isRepoMaster ? '立即开启' : '了解一下'}
        </Button>
        <Button className="ignore" onClick={() => closeGuide()}>
          忽略
        </Button>
      </div>
    </div>
  );
  const guideFives = (
    <div className="codeUp-guideOne">
      <div
        className="codeUp-guideOne-title"
        dangerouslySetInnerHTML={{ __html: '&#128161 智能评审，推荐最佳评审人' }}
      />
      <div className="codeUp-guideOne-conect">
        不确定邀请谁评审更合适？「智能评审」综合数据为你推荐合适的评审人
      </div>
      <div className="codeUp-guideOne-buttonGroup">
        <Button
          type="primary"
          className="createButton"
          onClick={() => {
            isRepomasterOk && isRepomasterOk();
          }}
        >
          {isRepoMaster ? '立即开启' : '了解一下'}
        </Button>
        <Button
          className="ignore"
          onClick={() => {
            closeGuide();
            isRepoMasterHander && isRepoMasterHander();
          }}
        >
          忽略
        </Button>
      </div>
    </div>
  );
  const ZoomoutHander = () => {
    const div = ref.current; // corresponding DOM node
    div.className += ' animate__zoomOutUp';
    track &&
      track('fold_new_user_tips', {
        type: guideStatus && guideStatus.step ? stepName[guideStatus.step + 1] || '' : '',
      });
    setTimeout(() => {
      setGuideCount(2);
      onChangePropsCount && onChangePropsCount(2);
    }, 1000);
  };
  const carouselnameClickHander = (v: IProject) => {
    onChangeStep && onChangeStep(v.step);
    if (v.step) {
      track(`click-step-${v.step}`);
    }
    const newValue = array.map((val) => {
      if (val.name === v.name) {
        return { ...val, active: true };
      } else {
        return { ...val, active: false };
      }
    });
    setArray(newValue);
  };
  const guideTwo = (
    <div className="codeUp-guideTwo" ref={ref}>
      <div className="codeUp-guideTwo-title">
        <div className="codeUp-guideTwo-left">
          {array.map((va, idx) => {
            if (va.active && va.status) {
              return (
                <div
                  key={va.name}
                  style={{ fontSize: idx + 1 === array.length ? '14px' : null }}
                  dangerouslySetInnerHTML={{
                    __html: va.completeTitle ? va.completeTitle : va.title,
                  }}
                />
              );
            } else if (va.active) {
              return (
                <div
                  key={va.name}
                  style={{ fontSize: idx + 1 === array.length ? '14px' : null }}
                  dangerouslySetInnerHTML={{ __html: va.title }}
                />
              );
            }
            return null;
          })}
        </div>
        <div className="codeUp-guideTwo-right">
          <div>库内能力探索</div>
          <img src={foldUp} onClick={ZoomoutHander} />
        </div>
      </div>
      <div className="codeUp-guideTwo-conect">
        <div className="codeUp-guideTwo-back">
          {array.map((v) => {
            if (v.active) {
              return (
                <div key={v.name}>
                  <img src={v.image} />
                  <div
                    className="codeUp-guideTwo-back-content-text"
                    style={{ paddingBottom: v.subMessage ? '4px' : null }}
                    // dangerouslySetInnerHTML={{ __html: `${v.message}` }}
                  >
                    {v.message}
                  </div>
                  {v.subMessage && <div>{v.subMessage}</div>}
                </div>
              );
            } else {
              return null;
            }
          })}
        </div>
      </div>
      <div className="codeUp-guideTwo-carousel">
        {array.map((v, idx) => {
          if (idx + 1 === array.length) {
            return null;
          } else {
            return (
              <div className="codeUp-guideTwo-carouselconent" key={v.name}>
                <div
                  className={`codeUp-guideTwo-carouselname ${v.status ? 'active' : ''} ${
                    v.active ? 'iactive' : ''
                  }`}
                  onClick={() => carouselnameClickHander(v)}
                  dangerouslySetInnerHTML={{ __html: !v.status ? v.name : '' }}
                />
                {idx + 2 !== array.length ? <span className="codeUp-guideTwo-span" /> : null}
              </div>
            );
          }
        })}
      </div>
    </div>
  );
  const guideThree = () => {
    const value = array.filter((v) => v.status);
    const valueLength = value.length === 6 ? 5 : value.length;
    return (
      <div className="codeUp-guideThree">
        <div className="codeUp-guideThree-header">
          <div
            className="codeUp-guideThree-title"
            onMouseDown={(e) => {
              if (e.button === 0 || !e.button) {
                isClick = true;
              }
            }}
            onMouseUp={() => {
              if (!isClick) return;
              setGuideCount(1);
              onChangePropsCount && onChangePropsCount(1);
            }}
          >
            库内探索
            <span style={{ paddingLeft: 15 }}>
              {valueLength}/{array.length - 1}
            </span>
          </div>
          <div className="codeUp-guideThree-close" style={{ padding: '0 12px', zIndex: 90 }}>
            {/* <img
              // src={close}
              title="关闭引导"
            /> */}
            <YunxiaoIcon
              type="false-line"
              onClick={(e) => {
                e.stopPropagation();
                closeGuide();
              }}
            />
          </div>
        </div>
        <div className="codeUp-guideThree-schedule">
          <Progress
            size="small"
            percent={(valueLength / (array.length - 1)) * 100}
            color="#7076e1"
            shape="line"
            backgroundColor={'#d4d4ec'}
            textRender={() => null}
          />
        </div>
      </div>
    );
  };
  const onDrag = () => {
    isClick = false;
  };

  if (getFeature('project.libraryInsideGuide.enable')) {
    return (
      <Draggable onDrag={onDrag} bounds={{ top: -2 }}>
        <div ref={codeupRef} className="codeUp-guide">
          {guideConent(guideCount)}
        </div>
      </Draggable>
    );
  } else {
    return null
  }

};

export default CodeUpGuide;
